<template>
    <el-container class="content">
        <el-main>
            <el-container class="white-block box full" v-loading="loading">
                <el-header :height="'auto'">
                    <breadcrumb :title="'患者管理'" :noBack="true"></breadcrumb>
                    <div class="toolbar">
                        <div>
                            <el-input v-model="name" placeholder="请输入姓名、住院号" class="input" clearable></el-input>
                            <!--                            <el-cascader v-model="ward" ref="floor" clearable-->
                            <!--                                         :separator="' '"-->
                            <!--                                         :show-all-levels="false"-->
                            <!--                                         @change="changeFloor"-->
                            <!--                                         :props="{label:'name',value:'treeId',children:'children'}"-->
                            <!--                                         :options="floorInfo">-->
                            <!--                                &lt;!&ndash;                                <template slot-scope="{ node, data }">&ndash;&gt;-->
                            <!--                                &lt;!&ndash;                                    <div>{{ data.name }}</div>&ndash;&gt;-->
                            <!--                                &lt;!&ndash;                                </template>&ndash;&gt;-->
                            <!--                            </el-cascader>-->
                            <el-date-picker
                                class="searchTime"
                                v-model="searchTime"
                                type="daterange"
                                :editable="false"
                                unlink-panels
                                start-placeholder="注册开始时间"
                                end-placeholder="注册结束时间"
                                range-separator="-">
                            </el-date-picker>
                            <el-button type="primary" @click="getList(1)">查询</el-button>
                        </div>
                        <div class="text-right">
                            <el-button class="primary" @click="openDialog">新增</el-button>
                            <el-button @click="dataExport()">导出</el-button>
                        </div>
                    </div>
                </el-header>
                <el-main class="mt10">
                    <table-example ref="table" :data="tableData" :tableColumn="header" :height="'100%'"
                                   :slotColumns="slotColumns">
                        <template slot="operation" slot-scope="scope">
                            <div class="operation">
                                <el-link type="primary" :underline="false"
                                         @click="$router.push($route.path+'/detail?id='+scope.row.id+'&state='+scope.row.patientState)">
                                    查看详情
                                </el-link>
                                <el-link type="primary" :underline="false" v-if="scope.row.patientState==0"
                                         @click="discharge(scope.row)">办理出院
                                </el-link>
                                <!--                                <el-link type="primary" :underline="false" v-if="scope.row.patientState==1">恢复住院</el-link>-->
                            </div>
                        </template>
                    </table-example>
                </el-main>
                <el-footer :height="'auto'" class="mt20">
                    <page :data="page" @jumpPage="getList"></page>
                </el-footer>
                <dialog-msk :show.sync="showCreate" title="添加患者" :width="'450px'" @save="savePatient"
                            @cancel="closeDialog" v-loading="contentLoading"
                            element-loading-background="rgba(0, 0, 0, 0.3)">
                    <el-form class="form-common" :model="patientNew" :rules="rulesSave" ref="createForm"
                             size="small" label-width="90px" :label-position="'left'">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="patientNew.name" size="small" placeholder="请填写姓名" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="身份证号" prop="idCard">
                            <el-input v-model="patientNew.idCard" size="small" placeholder="请填写身份证号"
                                      clearable></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="patientNew.phone" size="small" placeholder="请填写手机号" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="住院号" prop="admissionNumber">
                            <el-input v-model="patientNew.admissionNumber" size="small" placeholder="请填写住院号"
                                      clearable></el-input>
                        </el-form-item>
                        <el-form-item label="床位号" prop="sickbedNumber">
                            <el-cascader v-model="patientNew.sickbedNumber" ref="sickbed" clearable class="full"
                                         :separator="' '"
                                         :show-all-levels="false"
                                         placeholder="请选择床位号"
                                         @change="changeSickbed"
                                         :props="{label:'name',value:'treeId',children:'children',disabled: 'state'}"
                                         :options="sickbedInfo">
                            </el-cascader>
                        </el-form-item>
                    </el-form>
                </dialog-msk>
            </el-container>
            <transition name="slide">
                <router-view @upload="getList"></router-view>
            </transition>
        </el-main>
    </el-container>
</template>

<script>
    import tableExample from '../components/table'
    import page from '../components/pagination'
    import breadcrumb from '../components/breadcrumb'
    import dialogMsk from '../components/dialog'

    export default {
        data() {
            let validatePhone = (rule, value, callback) => {
                if (!/^1\d{10}$/.test(value)) {
                    callback(new Error('手机号格式错误'))
                } else {
                    callback()
                }
            }
            return {
                name: '', // 姓名
                searchTime: '',
                ward: [], // 病区
                tableData: [],
                header: [
                    {
                        prop: 'sickbedNumber',
                        label: '床位号',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'name',
                        label: '姓名',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'admissionNumber',
                        label: '住院号',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'escorNumber',
                        label: '陪护人数',
                        minWidth: '100',
                        align: 'center'
                    },
                    {
                        prop: 'operation',
                        label: '操作',
                        align: 'center',
                        minWidth: '150'
                    }
                ],
                slotColumns: ['operation'],
                page: {},
                index: 1,
                loading: false,
                floorInfo: [], // 病区tree
                sickbedInfo: [], // 病床tree
                showCreate: false,
                patientNew: {
                    name: '',
                    idCard: '',
                    admissionNumber: '', // 住院号
                    phone: '',
                    sickbedNumber: [] // 床位号
                },
                rulesSave: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: validatePhone, trigger: 'blur'}
                    ],
                    admissionNumber: [
                        {required: true, message: '请输入住院号', trigger: 'blur'}
                    ],
                    idCard: [
                        {required: true, message: '请输入身份证号', trigger: 'blur'}
                    ],
                    sickbedNumber: [
                        {required: true, message: '请选择床位号', trigger: 'change'}
                    ]
                },
                contentLoading: false
            }
        },
        mounted() {
            // this.searchTime = this.$filter.timeFormat(null, 'YYYY-MM-DD HH:mm:ss')
            this.getFloorInfo()
            this.getList()
        },
        methods: {
            getFloorInfo(index) {
                this.loading = true
                this.$http.get('/patient/getTree?type=3').then(result => {
                    this.loading = false
                    if (result.success) {
                        this.floorInfo = result.data
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            getSickbedInfo(callback) {
                this.loading = true
                this.$http.get('/patient/getTree?type=4').then(result => {
                    this.loading = false
                    if (result.success) {
                        this.sickbedInfo = result.data
                        if (callback) callback()
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            changeFloor(val) {
                console.log(this.$refs['floor'].getCheckedNodes(true))
            },
            changeSickbed(val) {
                console.log(this.$refs['sickbed'].getCheckedNodes(true))
            },
            // 获取列表数据
            getList(index) {
                this.loading = true
                if (index) this.index = index
                this.$http.get('/patient/patienPageQuery', {
                    startDate: (this.searchTime && this.searchTime.length) ? this.$filter.timeFormat(this.searchTime[0], 'YYYY-MM-DD') : '',
                    endDate: (this.searchTime && this.searchTime.length) ? this.$filter.timeFormat(this.searchTime[1], 'YYYY-MM-DD') : '',
                    content: this.name,
                    areaId: (this.ward && this.ward.length) ? this.$refs['floor'].getCheckedNodes(true)[0].data.id : '',
                    current: this.index || 1,
                    size: 15
                }).then(result => {
                    this.loading = false
                    if (result.success) {
                        this.tableData = result.data.records
                        this.page = result.data
                        delete this.page['records']
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            // 导出表格
            dataExport() {
                let params = {
                    startDate: (this.searchTime && this.searchTime.length) ? this.$filter.timeFormat(this.searchTime[0], 'YYYY-MM-DD') : '',
                    endDate: (this.searchTime && this.searchTime.length) ? this.$filter.timeFormat(this.searchTime[1], 'YYYY-MM-DD') : '',
                    content: this.name,
                    areaId: (this.ward && this.ward.length) ? this.$refs['floor'].getCheckedNodes(true)[0].data.id : ''
                }
                window.open(location.origin + this.$filter.appendUrlParams('/_api/patient/excelExport', params), '_blank')
            },
            // 办理出院
            discharge(item) {
                let _this = this
                this.$method.messageBox('confirm', '确定办理出院吗？', (action, instance) => {
                    if (action === 'confirm') {
                        _this.$http.post('/patient/patienDischarge?id=' + item.id).then(result => {
                            if (result.success) {
                                _this.getList()
                            }
                        })
                    }
                }, '', false, false)
            },
            // 新增患者
            openDialog() {
                let _this = this
                this.getSickbedInfo(() => {
                    _this.showCreate = true
                })
            },
            savePatient() {
                let _this = this
                this.validate('createForm', () => {
                    this.submitAdd(function () {
                        _this.closeDialog()
                    })
                })
            },
            validate(formName, callback) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (callback) callback()
                    } else {
                        return false
                    }
                })
            },
            submitAdd(callback) {
                this.contentLoading = true
                let params = {
                    sickbedId: this.$refs['sickbed'].getCheckedNodes(true)[0].data.id,
                    admissionNumber: this.patientNew.admissionNumber,
                    idCard: this.patientNew.idCard,
                    patientName: this.patientNew.name,
                    phone: this.patientNew.phone
                }
                this.$http.post('/patient/savePatien', params).then(result => {
                    this.contentLoading = false
                    if (result.success) {
                        this.$message.success({
                            message: '添加成功。',
                            showClose: true
                        })
                        this.getList()
                        if (callback) callback()
                    }
                }).catch(() => {
                    this.contentLoading = false
                })
            },
            closeDialog() {
                if (this.$refs.createForm) this.$refs.createForm.resetFields()
                this.showCreate = false
            }
        },
        components: {
            tableExample,
            page,
            breadcrumb,
            dialogMsk
        }
    }
</script>

<style scoped lang="less">
    .toolbar {
        .searchTime {
            width: 280px;
        }
    }
</style>
